package org.game.utils;

import java.util.Arrays;
import java.util.Random;

/**
 * 随机工具类
 * @author fangming
 * 2015年8月5日
 */
public class RandomUtil {

	private static Random random = new Random();
	
	/**
	 * 给定一个数n,返回一个0和n之间的随机数
	 * @param n 给的值
	 * @return 范围 [0 , n)
	 */
	public static int randomInt(int n) {
		return random.nextInt(n);
	}
	
	/**
	 * 给定一个范围,返回一个这个范围的随机数
	 * @param min
	 * @param max
	 * @return 范围[min,max)
	 */
	public static int randomInt(int min, int max) {
		return randomInt(max - min) + min;
	}
	
	/**
	 * 根据权重值,随机出一个索引
	 * @param weights 权值数组
	 * @return 数组索引
	 */
	public static int randomIndexByWeights(int[] weights) {
		if (weights == null || weights.length == 0) {
			throw new IllegalArgumentException("weights array is null or empty!");
		}
		int len = weights.length;
		int sum = 0;
		for (int n : weights) {
			sum += n;
		}
		if (sum <= 0) {
			throw new IllegalArgumentException("weights array error!" + Arrays.toString(weights));
		}
		int rand = random.nextInt(sum);
		int m = 0;
		int i = 0;
		do {
			m += weights[i];
			if (rand < m) {
				return i;
			}
			i++;
		} while (i < len);
		return len - 1;
	}
	
}
